<template>
	<view class="page">
		<!-- 头部 -->
		<!-- <view class="headerbox">
			<view class="headerBag">
				<image src="/static/icons/icon-Get-into@3.png" class="back" @click="goBack"></image>
				<text class="goumai">购买云主</text>
			</view>
		</view> -->

		<!-- 内容区域 -->
		<view class="content_box">
			<view class="box1">
				<text class="box1p">分享赚钱</text>
				<view class="shuju">
					<view class="shuju-item" v-for="(item, index) in dataList" :key="index">
						<image class="item-icon" :src="serverAddress +item.icon" alt=""></image>
						<text class="item-text">{{ item.text }}</text>
						<text class="item-value">{{ item.value }}</text>
					</view>
				</view>


			</view>

			<view class="box1">
				<view class="comt">
					<text class="comt-title">消费省钱</text>
					<view class="cont">
						<image :src="serverAddress +'/img/组 1@2x(3).png'" alt=""></image>
						<text class="save-value">{{ staffData.rebate_rate || '0%' }}</text>
					</view>
				</view>
			</view>
			<view class="tu">
				<image :src="serverAddress +'/img/组 1@2x(4).png'" alt=""></image>
			</view>


		</view>
		<!-- 立即开通按钮 -->
		 <view class="foot-container">
		      <view class="foot" @click="openPayment">
		        <text>立即开通</text>
		      </view>
		    </view>
		<!-- 支付方式弹窗 -->
		<view class="paymethod" v-if="showPayModal" @click="closePayModal">
			<view class="pay-content" @click.stop>
				<view class="close-btn" @click="closePayModal">×</view>
				<view class="pay-header">确认付款</view>
				<view class="show-amount">¥{{ staffData.price || '0.00' }}</view>

				<view class="pay-methods">
					<view class="method balance-pay" @click="selectPayMethod('balance')">
						<text>账户余额</text>
						<text class="balance-amount">¥{{ userBalance }}</text>
					</view>
					<view class="method wechat-pay" @click="selectPayMethod('wechat')">
						<text>微信支付</text>
						<image src="/static/icons/arrow-right.png"></image>
					</view>
					<!-- <view class="method union-pay" @click="selectPayMethod('union')">
						<text>银联支付</text>
						<image src="/static/icons/arrow-right.png"></image>
					</view> -->
				</view>
			</view>
		</view>

		<!-- 支付密码验证弹窗 -->
		<view class="password-modal" v-if="showPasswordModal">
			<view class="password-content">
				<view class="password-header">
					<image src="/static/icons/icon-Get-into@3.png" class="back" @click="closePasswordModal"></image>
					<text class="password-title">{{ passwordTitle }}</text>
				</view>
				<view class="password-wrapper">
					<text class="password-tip">{{ passwordTip }}</text>
					<view class="password-input">
						<input type="password" v-model="payPassword" maxlength="6" @input="onPasswordInput"
							:focus="showPasswordModal" />
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		identityApi,
		paymentApi
	} from '@/api/index.js'
	import md5 from 'md5'
	import {
		inject
	} from 'vue'
	export default {
		data() {
			return {
				baseUrl: inject('$baseUrl'),
				serverAddress: inject('$serverAddress', ''),
				staffData: {},
				userBalance: '0.00',
				showPayModal: false,
				showPasswordModal: false,
				payPassword: '',
				selectedPayMethod: '',
				passwordTitle: '验证支付密码',
				passwordTip: '请输入支付密码',
				isSettingPassword: false,
				firstPassword: '',
				secondPassword: '',
				dataList: [{
						icon: '/img/组 2(1).png',
						text: '邀请他人成为会员',
						value: '0'
					},
					{
						icon: '/img/组 2(1).png',
						text: '间接邀请他人成为会员',
						value: '0'
					},
					{
						icon: '/img/组 4@2x.png',
						text: '邀请他人成为云主',
						value: '0'
					},
					{
						icon: '/img/组 4@2x(1).png',
						text: '间接邀请他人成为云主',
						value: '0'
					},
					{
						icon: '/img/组 3@2x.png',
						text: '邀请他人成为合伙人',
						value: '0'
					},
					{
						icon: '/img/组 1.png',
						text: '邀请他人成为商家',
						value: '0'
					},
					{
						icon: '/img/组 1@2x(1).png',
						text: '邀请他人成为厂家',
						value: '0'
					},
					{
						icon: '/img/组 1@2x(2).png',
						text: '其他季节/年度活动的奖励',
						value: ''
					}
				]
			}
		},

		onLoad() {
			this.loadStaffData()
			this.loadUserBalance()
		},

		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 加载员工数据
			async loadStaffData() {
				try {
					const res = await identityApi.getStaffData()
					if (res.r === 0) {
						this.staffData = res.data
						// 更新数据列表
						this.dataList[0].value = res.data.invite_user || '0'
						this.dataList[1].value = res.data.ind_invite_user || '0'
						this.dataList[2].value = res.data.invite_staff || '0'
						this.dataList[3].value = res.data.ind_invite_staff || '0'
						this.dataList[4].value = res.data.invite_partner || '0'
						this.dataList[5].value = res.data.invite_merch || '0'
						this.dataList[6].value = res.data.invite_manufac || '0'
					}
				} catch (error) {
					console.error('加载员工数据失败:', error)
					uni.showToast({
						title: '加载数据失败',
						icon: 'none'
					})
				}
			},

			// 加载用户余额
			async loadUserBalance() {
				try {
					const res = await paymentApi.getUserBalance()
					if (res.r === 0) {
						this.userBalance = res.data.withdraw_money || '0.00'
					}
				} catch (error) {
					console.error('加载用户余额失败:', error)
				}
			},

			// 打开支付弹窗
			openPayment() {
				this.showPayModal = true
			},

			// 关闭支付弹窗
			closePayModal() {
				this.showPayModal = false
			},

			// 选择支付方式
			selectPayMethod(method) {
				this.selectedPayMethod = method

				if (method === 'balance') {
					// 检查余额是否足够
					const balance = parseFloat(this.userBalance)
					const price = parseFloat(this.staffData.price || 0)

					if (balance < price) {
						uni.showToast({
							title: '余额不足',
							icon: 'none'
						})
						return
					}

					// 显示支付密码验证
					this.showPasswordVerification()
				} else if (method === 'wechat') {
					this.wechatPay()
				} else if (method === 'union') {
					this.unionPay()
				}
			},

			// 显示支付密码验证
			async showPasswordVerification() {
				try {
					// 检查是否已设置支付密码
					const res = await paymentApi.checkPayPassword()
					if (res.r === 0) {
						if (res.data.is_set === 1) {
							// 已设置密码，验证密码
							this.passwordTitle = '验证支付密码'
							this.passwordTip = '请输入支付密码'
							this.isSettingPassword = false
						} else {
							// 未设置密码，设置密码
							this.passwordTitle = '设置支付密码'
							this.passwordTip = '请设置支付密码'
							this.isSettingPassword = true
						}
						this.showPayModal = false
						this.showPasswordModal = true
						this.payPassword = ''
					}
				} catch (error) {
					console.error('检查支付密码失败:', error)
				}
			},

			// 关闭密码弹窗
			closePasswordModal() {
				this.showPasswordModal = false
				this.payPassword = ''
				this.firstPassword = ''
				this.secondPassword = ''
			},

			// 密码输入处理
			onPasswordInput() {
				if (this.payPassword.length === 6) {
					if (this.isSettingPassword) {
						this.handleSetPassword()
					} else {
						this.handleVerifyPassword()
					}
				}
			},

			// 处理设置密码
			async handleSetPassword() {
				if (!this.firstPassword) {
					this.firstPassword = this.payPassword
					this.payPassword = ''
					this.passwordTip = '请再次输入支付密码'
				} else {
					this.secondPassword = this.payPassword

					if (this.firstPassword !== this.secondPassword) {
						uni.showToast({
							title: '两次密码输入不一致',
							icon: 'none'
						})
						this.payPassword = ''
						this.secondPassword = ''
						return
					}

					try {
						const res = await paymentApi.setPayPassword({
							pay_pwd: md5(this.firstPassword),
							pay_confirm_pwd: md5(this.secondPassword)
						})

						if (res.r === 0) {
							uni.showToast({
								title: '支付密码设置成功',
								icon: 'success'
							})
							this.isSettingPassword = false
							this.passwordTitle = '验证支付密码'
							this.passwordTip = '请输入支付密码'
							this.payPassword = ''
							this.firstPassword = ''
							this.secondPassword = ''
						} else {
							uni.showToast({
								title: res.msg || '设置失败',
								icon: 'none'
							})
						}
					} catch (error) {
						console.error('设置支付密码失败:', error)
					}
				}
			},

			// 处理验证密码
			async handleVerifyPassword() {
				try {
					const res = await paymentApi.verifyPayPassword({
						pay_pwd: md5(this.payPassword)
					})

					if (res.r === 0) {
						// 密码验证成功，执行支付
						this.closePasswordModal()
						this.executePayment()
					} else {
						uni.showToast({
							title: res.msg || '密码错误',
							icon: 'none'
						})
						this.payPassword = ''
					}
				} catch (error) {
					console.error('验证支付密码失败:', error)
					this.payPassword = ''
				}
			},

			// 执行支付
			async executePayment() {
				try {
					// 创建订单
					const orderRes = await identityApi.applyCloudWorker({
						type: 8, // 云主类型
						num: 1
					})

					if (orderRes.r !== 0) {
						uni.showToast({
							title: orderRes.msg || '创建订单失败',
							icon: 'none'
						})
						return
					}

					const orderNumber = orderRes.data.order_num

					// 余额支付
					const payRes = await paymentApi.balancePay({
						order_num: orderNumber,
						type: 8,
						num: 1
					})

					if (payRes.r === 0) {
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						})

						// 跳转到成功页面
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/identity/buyCooperative_succeed?idtype=8&payType=余额支付&totalp=${this.staffData.price}`
							})
						}, 1500)
					} else {
						uni.showToast({
							title: payRes.msg || '支付失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('支付失败:', error)
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}
			},

			// 微信支付
			async wechatPay() {
				try {
					// 创建订单
					const orderRes = await identityApi.applyCloudWorker({
						type: 8,
						num: 1
					})

					if (orderRes.r !== 0) {
						uni.showToast({
							title: orderRes.msg || '创建订单失败',
							icon: 'none'
						})
						return
					}

					const orderNumber = orderRes.data.order_num

					// 微信支付
					const payRes = await paymentApi.wechatPay({
						order_num: orderNumber,
						source: 5,
						type: 8,
						num: 1,
						openid: uni.getStorageSync('openid') || ''
					})

					if (payRes.r === 0) {
						// 调用微信支付
						this.callWechatPay(payRes.data)
					} else {
						uni.showToast({
							title: payRes.msg || '支付失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('微信支付失败:', error)
				}
			},

			// 调用微信支付
			callWechatPay(payData) {
				// #ifdef H5
				if (typeof WeixinJSBridge !== 'undefined') {
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
						appId: payData.appId,
						timeStamp: String(payData.timeStamp),
						nonceStr: payData.nonceStr,
						package: payData.package,
						signType: payData.signType,
						paySign: payData.paySign
					}, (res) => {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							uni.navigateTo({
								url: `/pages/identity/buyCooperative_succeed?idtype=8&payType=微信支付&totalp=${this.staffData.price}`
							})
						} else {
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							})
						}
					})
				}
				// #endif

				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: String(payData.timeStamp),
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: () => {
						uni.navigateTo({
							url: `/pages/identity/buyCooperative_succeed?idtype=8&payType=微信支付&totalp=${this.staffData.price}`
						})
					},
					fail: () => {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				})
				// #endif
			},

			// 银联支付
			async unionPay() {
				try {
					// 创建订单
					const orderRes = await identityApi.applyCloudWorker({
						type: 8,
						num: 1
					})

					if (orderRes.r !== 0) {
						uni.showToast({
							title: orderRes.msg || '创建订单失败',
							icon: 'none'
						})
						return
					}

					const orderNumber = orderRes.data.order_num

					// 银联支付
					const payRes = await paymentApi.unionPay({
						order_num: orderNumber,
						source: 2,
						type: 8,
						num: 1
					})

					if (payRes.r === 0) {
						// 跳转到银联支付页面
						const params = payRes.data.list.params
						let formHtml =
							'<form id="payForm" action="https://gateway.95516.com/gateway/api/frontTransReq.do" method="post">'

						for (let key in params) {
							formHtml += `<input type="hidden" name="${key}" value="${params[key]}" />`
						}
						formHtml += '</form>'

						// #ifdef H5
						document.body.innerHTML += formHtml
						document.getElementById('payForm').submit()
						// #endif
					} else {
						uni.showToast({
							title: payRes.msg || '支付失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('银联支付失败:', error)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background: #f7f7f7;
		height: 100vh;
		color: #4d4d4d;
		position: relative;
		overflow: hidden;
	}

	.headerbox {
		height: 160rpx;
		width: 100%;
		// background: url('/static/icons/header-bg.png') no-repeat center;
		background-size: 100% 72rpx;
		background-position-y: -4rpx;
	}

	.headerBag {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;

		.back {
			position: absolute;
			left: 30rpx;
			width: 40rpx;
			height: 40rpx;
		}

		.goumai {
			font-size: 36rpx;
			color: #fff;
			font-weight: bold;
			margin-top: 16rpx;
		}
	}

	.content_box {
		width: 670rpx;
		margin: 0 auto;
		position: relative;
		border-radius: 15rpx;
		margin-top: 20rpx;
		// padding-bottom: 160rpx;
	}

	.box1 {
		// width: 95%;
		// margin: 0 auto;
		padding: 20rpx;
		background: #fff;
		border-radius: 30rpx;
		margin-top: 30rpx;
	}

	.box1p {
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
		display: block;
		margin-bottom: 30rpx;
	}

	.shuju {
		width: 100%;
	}

	.shuju-item {
		height: 80rpx;
		position: relative;
		display: flex;
		align-items: center;

		image {
			width: 50rpx;
			height: 52rpx;
		}

		.item-icon {
			width: 26rpx;
			height: 28rpx;
		}

		.item-text {
			font-size: 26rpx;
			margin-left: 20rpx;
			flex: 1;
		}

		.item-value {
			font-size: 20rpx;
			color: #999999;
		}
	}

	.comt {
		width: 100%;
		height: 148rpx;
		background: #fff;
		border-radius: 15rpx;
		padding: 20rpx;
		box-sizing: border-box;

		.comt-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333333;
			display: block;
			margin-bottom: 30rpx;
		}

		.cont {
			display: flex;
			align-items: center;

			image {
				width: 50rpx;
				height: 50rpx;
			}

			.save-value {
				font-size: 26rpx;
				margin-left: 20rpx;
			}
		}
	}

	.tu {
		width: 100%;
		margin-top: 40rpx;
		text-align: center;

		image {
			width: 695rpx;
			height: 140rpx;
		}
	}
/* 底部按钮容器 */
.foot-container {
  // position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 40rpx 40rpx;
  background-color: #f7f7f7;
  z-index: 10;
}

.foot {
  width: 100%;
  height: 80rpx;
  background: #FF583C;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  text {
    font-size: 30rpx;
    color: #fff;
    font-weight: bold;
  }
}

	/* 支付弹窗样式 */
	.paymethod {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}

	.pay-content {
		width: 100%;
		background: #fff;
		border-radius: 20rpx 20rpx 0 0;
		padding: 40rpx;
		position: relative;
	}

	.close-btn {
		position: absolute;
		top: 20rpx;
		right: 30rpx;
		font-size: 40rpx;
		color: #999;
	}

	.pay-header {
		font-size: 32rpx;
		font-weight: bold;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.show-amount {
		font-size: 48rpx;
		font-weight: bold;
		text-align: center;
		color: #FF583C;
		margin-bottom: 40rpx;
	}

	.pay-methods {
		.method {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;
			border-bottom: 1rpx solid #f0f0f0;
			font-size: 34rpx;

			&:last-child {
				border-bottom: none;
			}

			image {
				width: 40rpx;
				height: 40rpx;
			}
		}

		.balance-pay {
			.balance-amount {
				color: #999;
				font-size: 28rpx;
			}
		}
	}

	/* 密码弹窗样式 */
	.password-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 1000;
	}

	.password-content {
		width: 100%;
		height: 100%;
		background: #fff;
	}

	.password-header {
		height: 100rpx;
		display: flex;
		align-items: center;
		padding: 0 30rpx;
		border-bottom: 1rpx solid #f0f0f0;

		.back {
			width: 40rpx;
			height: 40rpx;
		}

		.password-title {
			flex: 1;
			text-align: center;
			font-size: 36rpx;
			font-weight: bold;
		}
	}

	.password-wrapper {
		padding: 60rpx 40rpx;

		.password-tip {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 40rpx;
			display: block;
		}

		.password-input {
			input {
				width: 100%;
				height: 80rpx;
				border: 2rpx solid #ddd;
				border-radius: 10rpx;
				padding: 0 20rpx;
				font-size: 32rpx;
				text-align: center;
				letter-spacing: 10rpx;
			}
		}
	}
</style>